package utils

import (
	"encoding/json"
	"fmt"
	"log"
	"strings"
)

// StrictOpenAPIParser 严格的OpenAPI解析器，确保参数映射的准确性
type StrictOpenAPIParser struct {
	spec map[string]interface{}
}

// NewStrictOpenAPIParser 创建新的严格OpenAPI解析器
func NewStrictOpenAPIParser(specContent string) (*StrictOpenAPIParser, error) {
	var spec map[string]interface{}
	if err := json.Unmarshal([]byte(specContent), &spec); err != nil {
		return nil, fmt.Errorf("failed to parse OpenAPI spec: %w", err)
	}

	return &StrictOpenAPIParser{spec: spec}, nil
}

// ExtractParameterSchema 提取指定路径和方法的参数schema
func (sop *StrictOpenAPIParser) ExtractParameterSchema(path, method string) (map[string]interface{}, error) {
	paths, ok := sop.spec["paths"].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("no paths found in OpenAPI spec")
	}

	pathObj, ok := paths[path].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("path %s not found", path)
	}

	methodObj, ok := pathObj[strings.ToLower(method)].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("method %s not found for path %s", method, path)
	}

	// 优先提取requestBody schema
	if requestBody, ok := methodObj["requestBody"].(map[string]interface{}); ok {
		schema, err := sop.extractRequestBodySchema(requestBody)
		if err == nil {
			log.Printf("[STRICT_PARSER] Extracted requestBody schema for %s %s", method, path)
			return schema, nil
		}
	}

	// 提取parameters schema
	if parameters, ok := methodObj["parameters"].([]interface{}); ok {
		schema, err := sop.extractParametersSchema(parameters)
		if err == nil {
			log.Printf("[STRICT_PARSER] Extracted parameters schema for %s %s", method, path)
			return schema, nil
		}
	}

	return nil, fmt.Errorf("no parameter schema found for %s %s", method, path)
}

// extractRequestBodySchema 提取requestBody的schema
func (sop *StrictOpenAPIParser) extractRequestBodySchema(requestBody map[string]interface{}) (map[string]interface{}, error) {
	content, ok := requestBody["content"].(map[string]interface{})
	if !ok {
		return nil, fmt.Errorf("no content in requestBody")
	}

	// 尝试多种content type
	contentTypes := []string{"application/json", "application/x-www-form-urlencoded", "multipart/form-data"}
	for _, contentType := range contentTypes {
		if jsonContent, ok := content[contentType].(map[string]interface{}); ok {
			if schema, ok := jsonContent["schema"].(map[string]interface{}); ok {
				log.Printf("[STRICT_PARSER] Found schema in %s content type", contentType)
				return sop.normalizeSchema(schema), nil
			}
		}
	}

	return nil, fmt.Errorf("no valid schema found in requestBody content")
}

// extractParametersSchema 提取parameters的schema
func (sop *StrictOpenAPIParser) extractParametersSchema(parameters []interface{}) (map[string]interface{}, error) {
	schema := map[string]interface{}{
		"type":       "object",
		"properties": make(map[string]interface{}),
		"required":   []string{},
	}

	properties := schema["properties"].(map[string]interface{})
	var required []string

	for _, param := range parameters {
		paramObj, ok := param.(map[string]interface{})
		if !ok {
			continue
		}

		name, ok := paramObj["name"].(string)
		if !ok {
			continue
		}

		// 提取参数schema
		if paramSchema, ok := paramObj["schema"].(map[string]interface{}); ok {
			properties[name] = paramSchema
		} else {
			// 如果没有schema，创建基本的string类型
			properties[name] = map[string]interface{}{
				"type": "string",
			}
		}

		// 检查是否为必需参数
		if isRequired, ok := paramObj["required"].(bool); ok && isRequired {
			required = append(required, name)
		}
	}

	schema["required"] = required
	log.Printf("[STRICT_PARSER] Generated parameter schema with %d properties", len(properties))
	return schema, nil
}

// normalizeSchema 标准化schema，确保必要的字段存在
func (sop *StrictOpenAPIParser) normalizeSchema(schema map[string]interface{}) map[string]interface{} {
	normalized := make(map[string]interface{})

	// 复制所有字段
	for key, value := range schema {
		normalized[key] = value
	}

	// 确保有type字段
	if _, ok := normalized["type"]; !ok {
		normalized["type"] = "object"
	}

	// 确保有properties字段
	if _, ok := normalized["properties"]; !ok {
		normalized["properties"] = make(map[string]interface{})
	}

	// 确保有required字段
	if _, ok := normalized["required"]; !ok {
		normalized["required"] = []string{}
	}

	return normalized
}

// ValidateSchemaIntegrity 验证schema的完整性
func (sop *StrictOpenAPIParser) ValidateSchemaIntegrity(schema map[string]interface{}) error {
	// 检查基本结构
	if schemaType, ok := schema["type"].(string); !ok || schemaType != "object" {
		return fmt.Errorf("schema type must be 'object'")
	}

	properties, ok := schema["properties"].(map[string]interface{})
	if !ok {
		return fmt.Errorf("schema must have 'properties' field")
	}

	if len(properties) == 0 {
		return fmt.Errorf("schema properties cannot be empty")
	}

	// 验证required字段的有效性
	if required, ok := schema["required"].([]interface{}); ok {
		for _, reqField := range required {
			fieldName, ok := reqField.(string)
			if !ok {
				return fmt.Errorf("required field name must be string")
			}
			if _, exists := properties[fieldName]; !exists {
				return fmt.Errorf("required field '%s' not found in properties", fieldName)
			}
		}
	}

	log.Printf("[STRICT_PARSER] Schema integrity validation passed")
	return nil
}

// GetAllPaths 获取所有可用的路径和方法
func (sop *StrictOpenAPIParser) GetAllPaths() map[string][]string {
	result := make(map[string][]string)

	paths, ok := sop.spec["paths"].(map[string]interface{})
	if !ok {
		return result
	}

	for path, pathObj := range paths {
		if pathMap, ok := pathObj.(map[string]interface{}); ok {
			var methods []string
			for method := range pathMap {
				// 过滤掉非HTTP方法的字段
				if isHTTPMethod(method) {
					methods = append(methods, strings.ToUpper(method))
				}
			}
			if len(methods) > 0 {
				result[path] = methods
			}
		}
	}

	return result
}

// 注意：isHTTPMethod函数已在parser.go中定义，这里不重复定义